package com.demo.flight.service.impl;

import com.demo.flight.entity.Customer;
import com.demo.flight.entity.Order;
import com.demo.flight.entity.Seat;
import com.demo.flight.mapper.CustomerMapper;
import com.demo.flight.mapper.OrderMapper;
import com.demo.flight.mapper.SeatMapper;
import com.demo.flight.service.CustomerService;
import com.demo.flight.service.FlightService;
import com.demo.flight.service.OrderService;
import com.demo.flight.service.SeatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author ssy
 * @create 2022-03-24 19:31
 */

@Service
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private CustomerService customerService;
    
    @Autowired
    private FlightService flightService;
    
    @Autowired
    private SeatService seatService;
    
    @Override
    public List<Order> getAll() {
        return orderMapper.selectAll();
    }
    
    @Override
    public List<Order> getAllAvailable() {
        return orderMapper.selectAllAvailable();
    }
    
    @Override
    public List<Order> getAllNotAvailable() {
        return orderMapper.selectAllNotAvailable();
    }
    
    @Override
    public boolean add(Customer customer, Order order) {
        // 检查客户信息完整性
        if (customerService.checkComplement(customer)) {
            // 如果没有重复就创建新客户到customer表
            if (!customerService.checkIsDuplicated(customer)) {
                customerService.add(customer);
            }
            List<Customer> customers = customerService.getAllByCondition(customer);
            customer = customers.get(0);
            order.setCustomerId(customer.getCustomerId());
            // 如果flightId存在并且seat可用
            if (flightService.getOneById(order.getFlightId()) != null && seatService.checkSeatAvailable(order.getSeatId())) {
                // 前端已经保证客户信息、座位id、航班id非空，为订单加上创建时间，设置有效，插入订单
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                order.setOrderTime(sdf.format(new Date()));
                order.setOrderAvailable("yes");
                orderMapper.insert(order);
                return true;
            }
        }
        return false;
    }
    
    @Override
    public boolean cancelOrder(Integer orderId) {
        // 前端保证传入的orderId一定存在
        // 如果订单已经是取消状态则不能重复取消
        System.out.println(orderMapper.selectOrderState(orderId));
        if ("yes".equals(orderMapper.selectOrderState(orderId))) {
            orderMapper.updateOrderState(orderId, "no");
            return true;
        }
        return false;
    }
}
